package com.xzy.config;

import com.xzy.pojo.VoteUser;
import com.xzy.service.VoteUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class VoteUserRealm extends AuthorizingRealm {
    @Autowired
    VoteUserService voteUserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        System.out.println("执行授权代码块");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        VoteUser voteUser= (VoteUser) subject.getPrincipal();
        Set<String> permissions = new HashSet<String>();
        permissions.add(voteUser.getPerms());
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken token1= (UsernamePasswordToken) token;
        VoteUser voteUser= voteUserService.selectVoteUserByName(token1.getUsername());
        if(voteUser==null){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser",voteUser);
        return new SimpleAuthenticationInfo(voteUser,voteUser.getPassword(),"");
    }
}
